package com.kingbook.services;

import com.kingbook.core.base.SupportService;
import com.kingbook.core.result.JSONResult;
import com.kingbook.entity.Driver;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Bucky
 * @Date 2019-12-18 21:37:35
 * @Version 1.0
 */
@Slf4j
@Service
public class DriverService extends SupportService {

    @PostConstruct
    private void init() {
        setNamespace("Driver");
    }

    public JSONResult updateDriver( Map<String, Object> param ) {
        int mid = MapUtils.getIntValue(param, "mid");
        int id = MapUtils.getIntValue(param, "id");
        String name = MapUtils.getString(param, "name");
        Driver driver = queryDriverByName( mid, name);
        if (driver != null && driver.getId() !=id && name.equals(driver.getName()))
            return JSONResult.failed(name + " 已注册");
        return id > 0 ? modify(param) : save(param);
    }

    public int getDriverId(int mid, String name, boolean insert) {
        Map<String, Object> param = Maps.newHashMap();
        param.put("mid", mid);
        param.put("name", name);
        Driver driver = findObject("queryDriver", param, Driver.class);
        if (driver != null) {
            return driver.getId();
        } else if (insert) {
            JSONResult result = insertReturnKey("insert", param);
            return Integer.parseInt(result.getMsg());
        }
        return 0;
    }

    public Driver queryDriverByName( Integer mid, String name) {
        Map<String, Object> param = new HashMap<>(3);
        param.put("mid", mid);
        param.put("name", name);
        return findObject("queryDriver", param, Driver.class);
    }
}
